package server

import (
	"../chess"
)

type matcher struct {
	queue queue
	come  chan *chess.Player
}

func build() matcher {
	var array [10]*chess.Player
	queue := queue{
		array,
		0,
		0,
		0,
	}
	return matcher{
		queue,
		make(chan *chess.Player, 10),
	}
}

func (match *matcher) service() {
	for {
		select {
		case player := <-match.come:
			match.match(player)
		}
	}
}

func (match *matcher) match(player *chess.Player) {
	black := match.queue.take()
	if nil == black {
		match.queue.put(player)
	} else {
		room := chess.NewRoom(black, player)
		br := user{player.PlayerId()}
		player.SendMessage(br)
		wr := user{black.PlayerId()}
		black.SendMessage(wr)
		player.PieceColor(2)
		black.PieceColor(1)
		go room.Handle()
	}
}

type user struct {
	id uint32
}

type queue struct {
	queue [10]*chess.Player
	head  uint
	tail  uint
	size  uint
}

func (queue *queue) put(p *chess.Player) bool {
	if queue.size == 10 {
		return false
	}
	queue.tail = queue.tail + 1
	if queue.tail == 10 {
		queue.tail = 0
	}
	queue.queue[queue.tail] = p
	return true
}

func (queue *queue) take() *chess.Player {
	if queue.size == 0 {
		return nil
	}
	p := queue.queue[queue.head]
	queue.queue[queue.head] = nil
	queue.head = queue.head + 1
	if queue.head == 10 {
		queue.head = 0
	}
	return p
}
